package com.ly.jvm;

import java.util.concurrent.atomic.AtomicReference;

class User {
    private int age;

    private String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public User(int age, String name) {
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

public class AtomicReferenceDemo {

    public static void main(String[] args) {
        User u1 = new User(12,"a");
        User u2 = new User(22,"b");
        AtomicReference<User> r1 = new AtomicReference<>();
        r1.set(u1);
//        System.out.println(r1.compareAndSet(u1,u2)+" "+r1.get());
//        System.out.println(r1.compareAndSet(u1,u2));
//
        new Thread(()-> {
            r1.compareAndSet(u1,u2);
            u2.setAge(20);
            r1.compareAndSet(u2,u1);
        }).start();
        new Thread(()-> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(r1.compareAndSet(u1, u2));
        }).start();
    }
}
